<template>
  <el-dialog
    title="导入"
    :visible="dialogVisible"
    width="28%"
    @close="cancle"
  >
    <div class="main">
      <input ref="inputRef" accept=".xls, .xlsx, .png" style="display:none" type="file" @change="fileChangeTmp">
      <div class="content">
        <div class="top">
          <i class="el-icon-upload" />
        </div>
        <div class="middle" @click="downloadTemplateTmp">下载导入模板</div>
        <div class="bottom">
          <span>将文件拖到此处</span>
          <span @click="uploadFileTmp">点击上传</span>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="cancle">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { saveAs } from 'file-saver'
import { templateExportRequest, userImportRequest } from '@/api/employee'
export default {
  name: 'ImportExcelCom',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {

    }
  },
  computed: {
  },
  created() {
  },
  methods: {
    async downloadTemplateTmp() {
      const res = await templateExportRequest()
      // 将二进制保存为一个文件
      saveAs(res, '上传员工的模板文件.xlsx')
    },
    uploadFileTmp() {
      this.$refs.inputRef.click()
    },
    async fileChangeTmp(e) {
      // e.target.value --- 对应 type=text 的input输入框
      // e.target.files --- 对应 type=file 的输入框
      // console.log(e.target.files)
      const files = e.target.files
      console.log(files.length)
      if (files && files.length > 0) {
        // 在这里就要整理 发请求的参数 然后再发请求
        // 一般只要是发送文件给后端，一般都要用 FormData 这个对象去装file文件对象
        const formData = new FormData()
        formData.append('file', files[0])
        // debugger
        try {
          await userImportRequest(formData)
          // 当我们上传请求成功以后, 关闭弹出框, 刷新页面(发起后面获取列表的请求)
          this.cancle()

          // 子组件向父组件做任何交互, 都需要去 通知父组件($emit)
          this.$emit('import-success')
        } catch (_) {
          //
        } finally {
          // 无论请求成功或者失败，都要把已经上传的文件列表，清空，防止下次上传有bug
          this.$refs.inputRef.value = ''
        }
      }
    },
    cancle() {
      this.$emit('update:dialog-visible', false)
    }
  }
}
</script>
<style lang="scss">
.el-icon-upload::before {
  font-size: 50px;
  color: #afacac;
}
</style>
<style lang='scss'  scoped>
.main {
  border: 2px dashed #e0d9d9;
  border-radius: 8px;
  .content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
}
.middle {
  font-size: 18px;
  margin: 20px 0;
  color: #50acf2;
  cursor: pointer;
}
.bottom {
  span:first-child {
    color: #e0d9d9;
  }
  span:nth-child(2) {
    color: #50acf2;
    cursor: pointer;
  }
}
}
</style>
